import 'dart:async';

import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:provider/provider.dart';

import '../../../../lib_baseview/lib_baseview.dart';
import '../../../../lib_baseview/utils/constant/text_styles.dart';
import '../../../../lib_runtime/event_center.dart';
import '../../../../lib_runtime/logger.dart';
import '../../../../resource/language/generated/l10n.dart';
import '../../../m_chatroom.dart';

/// 麦位头像
class MicAvatarWidget extends StatefulWidget {
  static const msgShowMicImage = 'msg_show_mic_image';

  // final SimpleChannelUserSlot? item;
  final VoidCallback? onPressed;
  final double width;
  final int position;
  // final MicSeatScene micSeatScene;
  final Widget? rightLabel;
  final Widget? empty;
  final BoxBorder? border;
  final List<Widget>? avatarLabels;

  const MicAvatarWidget({
    super.key,
    // this.item,
    this.onPressed,
    this.width = 50,
    this.position = 0,
    // this.micSeatScene = MicSeatScene.ROOM,
    this.rightLabel,
    this.empty,
    this.border,
    this.avatarLabels,
  });

  @override
  State<MicAvatarWidget> createState() => _MicAvatarWidgetState();
}

class _MicAvatarWidgetState extends State<MicAvatarWidget> {
  String? roleTitle;

  StreamSubscription? _eventSub;
  // RoomMicShowImg? _micImg;
  late RootProxyModel roomModel;

  @override
  void initState() {
    super.initState();
    roomModel = context.read<RootProxyModel>();
    _eventSub = eventCenter
        .subscribe(MicSeatItemWidget.msgShowMicImage)
        .listen((event) {
      // if (event.data is! RoomMicShowImg) return;
      // RoomMicShowImg data = event.data;
      // if (data.imgUrl.isEmpty || data.offMicImgUrl.isEmpty) return;
      // if (data.type == 3) {
      //   ///播放完了隐藏麦上表情
      //   if (data.uid == widget.item?.user.id) {
      //     if (!mounted) return;
      //     _micImg = data;
      //   }
      // } else {
      //   if (data.uid == widget.item?.user.id) {
      //     if (!mounted) return;
      //     _micImg = data;
      //     Future.delayed(const Duration(seconds: 5), () {
      //       if (data.uid.toInt() == UserManager.instance.currentUid)
      //         roomModel.roomPageModel?.sendMicImgMsg(_micImg?.offMicImgUrl);
      //       _micImg = null;
      //       if (mounted) setState(() {});
      //     });
      //   }
      // }
    });

    if (needShowFollowUI) {
      Future.delayed(const Duration(seconds: 3)).then((value) {
        roomModel.followUid = 0;
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  Widget get emptyMic {
    var defaultIcon = Image.asset(
      'assets/images/mic_seat_place_holder.png',
      width: widget.width,
      height: widget.width,
      fit: BoxFit.cover,
    );
    // if (widget.item?.wheatStyleUrl.isNotEmpty ?? false) {
    //   return CachedNetworkImage(
    //       imageUrl: widget.item!.wheatStyleUrl,
    //       width: widget.width,
    //       height: widget.width,
    //       placeholder: (_, url) => defaultIcon,
    //       errorWidget: (_, url, err) => defaultIcon,
    //       fit: BoxFit.cover);
    // } else {
    return defaultIcon;
    // }
  }

  Widget get empty => widget.empty ?? emptyMic;

  BoxBorder? get border {
    return null;
    // return widget.border ??
    //     ((widget.item?.user.avatar.isNotEmpty ?? false)
    //         ? Border.all(color: const Color(0x4CFFFFFF), width: 1)
    //         : null);
  }

  GlobalKey? get avatarGlobalKey {
    // if (widget.micSeatScene == MicSeatScene.ROOM &&
    //     widget.item != null &&
    //     widget.item!.user.id.toInt() > 0) {
    //   return roomModel.getMicGlobalKey(widget.item!.user.id.toInt());
    // }
    return null;
  }

  // bool get needShowFollowUI =>
  //     roomModel.followUid > 0 &&
  //     roomModel.followUid == widget.item?.user.id.toInt();

  bool get needShowFollowUI => true;

  // Widget get avatar => AvatarImage(
  //       key: avatarGlobalKey,
  //       url: StringUtil.formatImgUrl(widget.item?.user.avatar, size: 150),
  //       width: widget.width,
  //       height: widget.width,
  //       borderRadius: widget.width / 2,
  //       fit: BoxFit.cover,
  //       border: border,
  //       placeholder: (_, url) => empty,
  //       errorWidget: (_, url, err) => empty,
  //     );

  // bool get showMicEffect => widget.item?.user.micEffect.isNotEmpty == true;
  bool get showMicEffect => true;
  Widget get micEffectWidget {
    // if (roomModel.isTalking(widget.item)) {
    //   return JR.img(
    //     widget.item!.user.micEffect,
    //     width: widget.width * 1.6,
    //     height: widget.width * 1.6,
    //     fit: BoxFit.cover,
    //   );
    // }
    return Text('micEffectWidget');
    // return const SizedBox.shrink();
  }

  Widget get waveBorder {
    return Text('waveBorder');
    // return ValueListenableBuilder(
    //     valueListenable: roomModel.speakers,
    //     builder: (context, value, child) {
    //       return showMicEffect
    //           ? micEffectWidget
    //           : WaveBorder(
    //               width: widget.width,
    //               maxWidth: widget.width * 1.6,
    //               borderWidth: 1.5,
    //               duration: const Duration(milliseconds: 1000),
    //               speaking: roomModel.isTalking(widget.item),
    //             );
    //     });
  }

  Widget get micImageWidget {
    return Text('micImageWidget');
    // if (_micImg?.type == 1) {
    //   return image(_micImg?.imgUrl ?? '',
    //       width: widget.width * 1.3, height: widget.width * 1.3);
    // } else if (_micImg?.type == 2) {
    //   return PAGView.network(
    //     _micImg?.imgUrl ?? '',
    //     width: widget.width * 1.3,
    //     height: widget.width * 1.3,
    //     autoPlay: true,
    //   );
    // } else if (_micImg?.type == 3) {
    //   return MultiFrameImage.network(_micImg?.imgUrl ?? '', 'mic_emote',
    //       width: widget.width * 1.3,
    //       height: widget.width * 1.3, onComplete: () {
    //     RLog.d('MultiFrameImage:onComplete');
    //     setState(() {
    //       _micImg = null;
    //     });
    //   });
    // }
    // return const SizedBox();
  }

  // bool get showOffline =>
  //     (widget.item?.user.offline ?? 0) == 1 &&
  //     (widget.item?.user.id.toInt() ?? 0) > 0;

  bool get showOffline => false;
  Widget get offLine => Container(
        width: widget.width,
        height: widget.width,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.4), shape: BoxShape.circle),
        child: const Text(
          '  T.current.offline',
          style: TextStyle(fontSize: 11, color: Colors.white),
        ),
      );

  // Channel? get channel => roomModel.channel;

  VoidCallback get onPressed =>
      widget.onPressed ??
      () {
        // if (widget.item?.user != null &&
        //     (widget.item?.user.id.toInt() ?? 0) > 0) {
        //   RoomPersonalDataWidget.show(context, channel, widget.item!.user,
        //       secretUser: widget.item!.user.secretUser == 1);
        // } else {
        //   roomModel.joinMicWithPosition(context, widget.position);
        // }
        showToast('上麦申请');
      };

  Widget get root {
    Widget frameWidget = SizedBox.shrink();
    var frameSize = widget.width * 1.25;
    // if (widget.micSeatScene == MicSeatScene.SEAT_FRAME_SETTING) {
    //   bool showFrameUrl = false;
    //   String frameUrl = '';
    //   //设置了以设置为准 否则显示默认的
    //   if (roomModel.changedItemConfigMap.isNotEmpty ?? false) {
    //     MicResourceConfigItem? micResourceConfigItem =
    //         roomModel.changedItemConfigMap[widget.position];
    //     if (micResourceConfigItem != null &&
    //         micResourceConfigItem.id.toInt() > 0) {
    //       showFrameUrl = true;
    //       frameUrl = micResourceConfigItem!.url;
    //     }
    //   } else {
    //     SimpleChannelUserSlot? slot =
    //         roomModel.channel?.broadcaster[widget.position];
    //     if (slot?.micFrameUrl.isNotEmpty ?? false) {
    //       showFrameUrl = true;
    //       frameUrl = slot?.micFrameUrl ?? '';
    //     }
    //   }

    //   if (showFrameUrl) {
    //     frameWidget = CachedNetworkImage(
    //       imageUrl: frameUrl,
    //       width: frameSize,
    //       height: frameSize,
    //       fit: BoxFit.cover,
    //     );
    //   }
    // } else if (widget.item?.micFrameUrl.isNotEmpty ?? false) {
    //   frameWidget = CachedNetworkImage(
    //     imageUrl: widget.item!.micFrameUrl,
    //     width: frameSize,
    //     height: frameSize,
    //     fit: BoxFit.cover,
    //   );
    // } else if (widget.item?.user.avatarFrame.isNotEmpty == true) {
    //   // 用户自己的头像框
    //   frameWidget = JR.img(
    //     widget.item!.user.avatarFrame,
    //     width: frameSize,
    //     height: frameSize,
    //     fit: BoxFit.cover,
    //   );
    // }

    return GestureDetector(
      onTap: onPressed,
      child: SizedBox(
        width: widget.width,
        height: widget.width,
        child: Stack(
          alignment: Alignment.center,
          clipBehavior: Clip.none,
          children: [
            _overFlowBox(waveBorder),
            Text('sssss'),
            // avatar,
            // if (showOffline) offLine,
            // _overFlowBox(frameWidget),
            // if (widget.item?.audition ?? false)
            //   const Align(
            //     alignment: Alignment.bottomCenter,
            //     child: TestVoiceLabel(),
            //   ),
            // topRightLabel,
            // ...widget.avatarLabels ?? [],
            // if (_micImg != null) _overFlowBox(micImageWidget),
            followTips
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) => root;

  Widget get followTips {
    if (needShowFollowUI) {
      return _overFlowBox(
          Container(
            margin: EdgeInsetsDirectional.only(bottom: widget.width + 25),
            padding: const EdgeInsetsDirectional.only(bottom: 5),
            width: 80,
            height: 23,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage(imagePath('room_follow_tips_img.png')),
                    fit: BoxFit.fill)),
            alignment: AlignmentDirectional.center,
            child: Text(
              '👋 ${T.current.hey_there}',
              style: JRTextStyles.styleFont11W400,
            ),
          ),
          maxScale: 2.0);
    }
    return const SizedBox.shrink();
  }

  Widget get topRightLabel {
    return Text('topRightLabel');
    // if (widget.rightLabel != null) {
    //   return Positioned(top: 0, right: 0, child: widget.rightLabel!);
    // } else if ((widget.item?.hasUser() ?? false) &&
    //     channel?.giftValueCountSwitch == true) {
    //   return Positioned(
    //       top: 0,
    //       left: 0.7 * widget.width,
    //       child: MicContributionLabel(
    //           contribution: widget.item?.contributionValue.toInt() ?? 0));
    // } else {
    //   return const SizedBox();
    // }
  }

  Widget _overFlowBox(Widget item, {double maxScale = 1.6}) {
    return OverflowBox(
        minWidth: widget.width,
        minHeight: widget.width,
        maxWidth: widget.width * maxScale,
        maxHeight: widget.width * maxScale,
        child: item);
  }

//  千转换成K
  String roomHeatTreatment(int? heat) {
    if (heat! > 1000) {
      double tmpHeat = heat / 1000;
      tmpHeat.toStringAsFixed(1);

      return tmpHeat.toStringAsFixed(1) + "k";
    } else {
      return heat.toString();
    }
  }

  @override
  void dispose() {
    _eventSub?.cancel();
    _eventSub = null;

    super.dispose();
  }
}
